<?php
declare(strict_types=1);

namespace App\Jobs\RoomPK;


use App\Enums\RoomPKEnum;
use App\Exceptions\BasicException;
use App\Jobs\Job;
use App\Repositories\RoomPk\RoomPKPitRepository;
use App\Repositories\RoomPk\RoomPKPitScoreLogRepository;
use App\Repositories\RoomPk\RoomPKRepository;
use App\Repositories\RoomPk\RoomPKScoreLogRepository;
use App\Services\Tools\PushService;
use Illuminate\Support\Facades\DB;

class PKGiftJob extends Job
{
    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        try {
            echo "pk送礼: {$this->data['room_id']}" . PHP_EOL;
            $roomId = $this->data["room_id"];
            if (empty($roomId)) {
                return false;
            }
            $room = app("model_user_room")
                ->where("id", $roomId)
                ->where("pk_status", RoomPKEnum::GAME_STATUS_PLAY)
                ->select(["room_pk_id", "pit_pk_id"])
                ->first();
            // print_r($room->toArray());

            // 是否正在进行房间id
            // $roomPkModel = RoomPKRepository::getInstance()->getPlayingRecord($roomId);
            // if(!empty($roomPkModel)){
            //     $this->roomPKGift($roomPkModel->id);
            // }
            if ($room->room_pk_id > 0) {
                $this->roomPKGift($room->room_pk_id);
            }

            // 是否正在进行麦位pk
            // $pitPKModel = RoomPKPitRepository::getInstance()->getPlayingRecord($roomId);
            // if(!empty($pitPKModel)){
            //     $this->pitPKGift($pitPKModel->id);
            // }
            if ($room->pit_pk_id > 0) {
                $this->pitPKGift($room->pit_pk_id);
            }
        } catch (\Exception $e) {
            file_put_contents(
                storage_path() . '/logs/pk-job-' . date('Ymd') . '.log',
                "name: PKGiftJob, message: {$e->getMessage()}, line: {$e->getLine()}, file: {$e->getFile()}" . PHP_EOL, FILE_APPEND
            );
            throw new BasicException($e->getCode(), $e->getMessage());
        }
    }

    public function roomPKGift(int $pkId)
    {
        // echo "pkId 送礼: $pkId, 麦位: {$this->data["pit_number"]}" . PHP_EOL;
        if (empty($this->data["pit_number"])) {
            return false;
        }
        $gift = app("model_gift")->newQuery()->where("id", $this->data["gift_id"])->first();
        $score = $gift->pk_score ? $gift->pk_score * $this->data["number"] : 0;
        // echo "礼物分数: {$score}, 礼物数量: {$this->data['number']}, 变更分数: $score" . PHP_EOL;
        DB::beginTransaction();
        try {
            $model = RoomPKRepository::getInstance()->find($pkId);
            if ($this->data["room_id"] == $model->room_id) {
                $model->score += $score;
                $camp = RoomPKEnum::ROOM_PK_CAMP_INITIATE;
            } else {
                $model->match_score += $score;
                $camp = RoomPKEnum::ROOM_PK_CAMP_MATCH;
            }
            $model->coin += $gift->price;
            $model->save();

            RoomPKScoreLogRepository::getInstance()->create([
                "pk_id" => $model->id,
                "log_id" => $this->data["id"],
                "room_id" => $this->data["room_id"],
                "user_id" => $this->data["gift_user"], // 收礼用户
                "contributor_user_id" => $this->data["user_id"], // 送礼用户
                "pit" => $this->data["pit_number"],
                "camp" => $camp,
                "score" => $score,
                "after_score" => $model->score,
                "coin" => $this->data['total_price'],
            ]);
            DB::commit();
        } catch (\Exception $e) {
            echo "异常" . $e->getMessage() . PHP_EOL;
            DB::rollBack();
            file_put_contents(
                storage_path() . '/logs/pk-job-' . date('Ymd') . '.log',
                "name: PKGiftJob-roomPKGift, message: {$e->getMessage()}, line: {$e->getLine()}, file: {$e->getFile()}" . PHP_EOL, FILE_APPEND
            );
            throw new BasicException($e->getCode(), $e->getMessage());
        }
        // 追加双方贡献者
        $model = RoomPKRepository::getInstance()->detail($pkId);
        $contributors = RoomPKScoreLogRepository::getInstance()->getContributorRankByCamp($model->id, RoomPKEnum::ROOM_PK_CAMP_INITIATE, 3);
        $matchContributors = RoomPKScoreLogRepository::getInstance()->getContributorRankByCamp($model->id, RoomPKEnum::ROOM_PK_CAMP_MATCH, 3);
        $model->contributors = $contributors->toArray() ?: null;
        $model->matchContributors = $matchContributors->toArray() ?: null;

        $public_room_id = $model->room_id > $model->match_room_id ? $model->room_id . '_' . $model->match_room_id : $model->match_room_id . '_' . $model->room_id;

        (new PushService(0, $public_room_id))->roomPKScore($model);
        // echo "调试5" . PHP_EOL;
//        (new PushService(0, $model->match_room_id))->roomPKScore($model);
        // echo "调试6" . PHP_EOL;
    }

    public function pitPKGift(int $pkId)
    {
        if (empty($this->data["pit_number"]) || $this->data["pit_number"] == 9) {
            return false;
        }
        $gift = app("model_gift")->newQuery()->where("id", $this->data["gift_id"])->first();
        $score = $gift->pk_score ? $gift->pk_score * $this->data["number"] : 0;
        // echo "礼物分数: {$score}, 礼物数量: {$this->data['number']}, 变更分数: $score" . PHP_EOL;
        DB::beginTransaction();
        try {
            $model = RoomPKPitRepository::getInstance()->findLock($pkId);
            if (in_array($this->data["pit_number"], explode(",", $model->red_pits))) {
                $model->red_score += $score;
                $camp = RoomPKEnum::PIT_PK_CAMP_RED;
            } else {
                $model->blue_score += $score;
                $camp = RoomPKEnum::PIT_PK_CAMP_BLUE;
            }
            $model->coin += $gift->price;
            $model->save();
            // echo "分数信息: red: {$model->red_score}, blue: {$model->blue_score}" . PHP_EOL;

            RoomPKPitScoreLogRepository::getInstance()->create([
                "pk_id" => $model->id,
                "log_id" => $this->data["id"],
                "room_id" => $model->room_id,
                "user_id" => $this->data["gift_user"], // 收礼用户
                "contributor_user_id" => $this->data["user_id"], // 送礼用户
                "pit" => $this->data["pit_number"],
                "camp" => $camp,
                "score" => $score,
                "after_score" => $camp == RoomPKEnum::PIT_PK_CAMP_RED ? $model->red_score : $model->blue_score,
                "coin" => $this->data['total_price'],
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            file_put_contents(
                storage_path() . '/logs/pk-job-' . date('Ymd') . '.log',
                "name: PKGiftJob-pitPKGift, message: {$e->getMessage()}, line: {$e->getLine()}, file: {$e->getFile()}" . PHP_EOL, FILE_APPEND
            );
            throw new BasicException($e->getCode(), $e->getMessage());
        }


        (new PushService(0, $model->room_id))->roomPitPKScore($pkId, $model->red_score, $model->blue_score);
    }

}
